﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using VideoRentalShop.Model;

namespace VideoRentalShop.Controller.Data
{
    public class MovieDataSource : DataSourceBase<Movie>
    {
        private OrderDetailsDataSource _orderDetailsSource;
        private GenreDetailsDataSource _genreDetailsSource;


        public MovieDataSource(MovieDbContext db, OrderDetailsDataSource orderDetailsSource, GenreDetailsDataSource genreDetailsSource) : base(db)
        {
            _orderDetailsSource = orderDetailsSource;
            _genreDetailsSource = genreDetailsSource;
        }


        public DbSet<Movie> GetAll()
        {
            return _db.Movies;
        }


        public override bool IsValid(Movie item)
        {
            return _db.Entry(item).GetValidationResult().IsValid;
        }

        public override bool Add(Movie item)
        {
            var entry = _db.Entry<Movie>(item);
            var valid = entry.GetValidationResult().IsValid;
            if (valid)
            {
                entry.State = EntityState.Added;
                return Save();
            }

            return valid;
        }

        public override bool Edit(Movie item)
        {
            var old = _db.GenreDetails.Where(x => x.MovieId == item.Id).ToList();
            var test = old.Count();
            for (var i = 0; i < test; ++i)
            {
                _db.Entry(old[i]).State = EntityState.Deleted;
            }

            var entry = _db.Entry<Movie>(item);
            var valid = entry.GetValidationResult().IsValid;
            if (valid)
            {
                entry.State = EntityState.Modified;
                return Save();
            }

            return valid;
        }

        public override bool Remove(Movie item)
        {
            var result = _db.Movies.Find(item.Id);
            if (result != null)
            {
                _orderDetailsSource.Remove(item);
                _genreDetailsSource.Remove(item);
                _db.Entry(result).State = EntityState.Deleted;
                return Save();
            }

            return false;
        }
    }
}
